package com.eyas.business.config.webmvc.interceptor;

import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: 王龙龙
 * @Date: 2019/2/26 09:18
 * @Description:
 */
public class LoginInterceptor implements HandlerInterceptor {
    public final static String LONGIN_SESSION_NAME = "eyas.website1.session.login";
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //用于校验登录情况
        return this.validLogin(request,response);
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }


    /**
     * admin system session拦截
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    private boolean validLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //当session不存在的时候
        if(request.getSession().getAttribute(LoginInterceptor.LONGIN_SESSION_NAME)==null||request.getSession().getAttribute(LoginInterceptor.LONGIN_SESSION_NAME).equals("")) {
            //当夜幕要跳转到登录页面或者要执行登录方法的时候，放行
            if(request.getRequestURI().indexOf("/eyas/admin/pagegoto/login")>-1||request.getRequestURI().indexOf("/eyas/admin/login")>-1) {
                return true;
            }
            //否则，重定向到登录页面并重新发送请求
            response.sendRedirect(request.getContextPath()+"/eyas/admin/pagegoto/login");
            return false;
        }else {
            //当session存在的时候，如果需要再次访问登录页面或者登录方法，直接重定向到index页面，重新发送请求
            if(request.getRequestURI().indexOf("/eyas/admin/pagegoto/login")>-1||request.getRequestURI().indexOf("/eyas/admin/login")>-1) {
                response.sendRedirect(request.getContextPath()+"/eyas/admin/pagegoto/index");
                return false;
            }
            return true;
        }
    }
}
